package com.simplenix.nicasio.textparser;

import com.simplenix.nicasio.def.Feature;
import com.simplenix.nicasio.misc.AppConfiguration;
import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.misc.Internationalization;
import com.simplenix.nicasio.misc.StrUtil;
import com.simplenix.nicasio.sys.SystemDef;
import com.simplenix.nicasio.tags.util.LoadMenu;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author fronald
 */
public class TextParser {

	public static final String SURROUND_CHAR = "@";

	public static String parseString(String str) {
		List<String> keys = getKeys(str);
		for (String key : keys) {
			if (key.equals("contextPath")) {
				str = str.replaceAll(SURROUND_CHAR + key + SURROUND_CHAR, SystemDef.getInstance().getContextPath());
			} else {
				try {
					str = Internationalization.getInstance().getString(key).equals(key) ? str : str.replaceAll(SURROUND_CHAR + key + SURROUND_CHAR, Internationalization.getInstance().getString(key));
					str = AppConfiguration.getInstance().getKey(key).equals(key) ? str : str.replaceAll(SURROUND_CHAR + key + SURROUND_CHAR, AppConfiguration.getInstance().getKey(key));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return str;
	}

	public static String parseKeyTags(String str, Feature feature, HttpServletRequest request) throws AppException {
		List<String> keys = getKeys(str);
		for (String key : keys) {
			if (key.equals("_topMenu_")) {
				str = str.replaceAll(SURROUND_CHAR + key + SURROUND_CHAR, StrUtil.nvl(LoadMenu.getHtmlByFeature(feature, request)));
			} else if (key.equals("_contextMenu_")) {
				str = str.replaceAll(SURROUND_CHAR + key + SURROUND_CHAR, StrUtil.nvl(LoadMenu.getContextMenuByFeature(feature)));
			}
		}
		return str;
	}

	private static List<String> getKeys(String str) {
		List<String> keys = new ArrayList<String>();
		String key = "";
		boolean get = false;
		for (int i = 0; i < str.length(); i++) {
			String c = str.charAt(i) + "";
			if (c.equals(SURROUND_CHAR)) {
				get = !get;
			}
			if (get) {
				if (!c.equals(SURROUND_CHAR)) {
					key += c;
				}
			} else if (!key.equals("")) {
				keys.add(key);
				key = "";
			}
		}
		return keys;
	}

}
